package com.ctrip.ec.api.admin.controller.agent;
import com.ctrip.ec.api.admin.common.Encryption;
import com.ctrip.ec.api.admin.common.ValidateException;
import com.ctrip.ec.api.admin.model.query.QueryModel;
import com.ctrip.ec.biz.dao.role.RoleUserDao;
import com.ctrip.ec.biz.dao.user.UserDao;
import com.ctrip.ec.biz.entity.agent.AgentModel;
import com.ctrip.ec.biz.entity.role.RoleUserEntity;
import com.ctrip.ec.biz.entity.role.SysRole;
import com.ctrip.ec.biz.entity.user.UserEntity;
import com.ctrip.ec.dal.PagerSetting;
import com.ctrip.ec.api.admin.common.RequestContext;
import com.ctrip.ec.biz.dao.agent.AgentDao;
import com.ctrip.ec.biz.entity.agent.AgentEntity;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("agent")
public class AgentController{
    @Autowired
    private AgentDao agent;

    @Autowired
    private UserDao user;

    @Autowired
    private RoleUserDao roleUser;

    @PostMapping("list")
    public List<AgentModel> list(@RequestBody QueryModel model) throws  SQLException{
        PagerSetting setting = model.build();
        List<AgentEntity> list = agent.list(setting);
        RequestContext.setResponseHeaderCount(setting.getRecordCount());
        List<AgentModel> modelList = new ArrayList<>();
        List<UserEntity> userList = user.listByIds(list.stream().map(t->t.getUserId()).collect(Collectors.toList()));


        for(AgentEntity entity : list){
            AgentModel model1 = new AgentModel(entity);
            model1.setLoginName(userList.stream().filter(t->t.getId().equals(entity.getUserId())).findFirst().get().getLoginName());

            modelList.add(model1);
        }
        return modelList;
    }

    @GetMapping("detail/{id}")
    public  AgentModel detail(@PathVariable Long id) throws SQLException {

        AgentEntity entity =  agent.entity(id);
        AgentModel model = new AgentModel(entity);
        if(entity.getUserId() != null && entity.getUserId() !=0){
            UserEntity userEntity = user.entity(entity.getUserId());
            if(userEntity != null){
                model.setLoginName(userEntity.getLoginName());
                model.setPassword(userEntity.getPassword());
            }
        }

        return model;

    }

    @PostMapping("save")
    public  Long save(@RequestBody AgentModel entity) throws Exception {

        UserEntity userEntity = user.entityByLoginName(entity.getLoginName());
        if(entity.add()) {
            if(Strings.isNullOrEmpty(entity.getLoginName())){
                throw new ValidateException("用户登录名不能为空");
            }
            if(Strings.isNullOrEmpty(entity.getPassword())){
                throw new ValidateException("用户密码不能为空");
            }
            if (userEntity == null) {
                userEntity = new UserEntity();
                userEntity.setLoginName(entity.getLoginName());
                userEntity.setPassword(Encryption.md5(entity.getPassword()));
                userEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                user.save(userEntity);

                //加入默认角色
                RoleUserEntity roleUserEntity = new RoleUserEntity();
                roleUserEntity.setUserId(userEntity.getId());
                roleUserEntity.setRoleId(SysRole.agent.getId());
                roleUser.save(roleUserEntity);

                entity.setUserId(userEntity.getId());
            } else {
                throw new ValidateException("系统已经存在相同的登录名");
            }
        }else {
            if (!userEntity.getPassword().equals(entity.getPassword())) {
                userEntity.setPassword(Encryption.md5(entity.getPassword()));
                user.save(userEntity);
            }
        }
        agent.save(entity);
        return entity.getId();
    }

    @PostMapping("delete")
    public  void delete(@RequestBody List<Long> ids) throws SQLException {
        agent.delete(ids);
    }
    @PostMapping("erase")
    public void erase(@RequestBody List<Long> ids) throws  SQLException{
        agent.erase(ids);
    }

    @PostMapping("unerase")
    public  void unerase(@RequestBody List<Long> ids) throws  SQLException{
        agent.unerase(ids);
    }
}
